package be.xios.projectquiz.jury;

import java.io.IOException;

import javax.swing.JFrame;

import be.xios.projectquiz.game.Game;
import be.xios.projectquiz.game.GameJuryGUI;
import be.xios.projectquiz.global.ScreenMethods;
import be.xios.projectquiz.global.SharedItems;
import be.xios.projectquiz.global.StreamMethods;
import be.xios.projectquiz.profiles.Jury;

/// <summary>
/// Deze klasse verzorgt het spelverloop van zaalquiz tussen jury en blokken
/// </summary>
/// <author>Sebastian Kubski</author>
/// <author>Sonny Valkeneers: spelverlopen gesplits voor jury</author>
public class JuryClientZaalQuiz implements Runnable{

	private GameJuryGUI gameGUI;
	private Game currentGame;
	private SharedItems shared;
	private StreamMethods streamMethods;
	private Jury jury;
	
	public JuryClientZaalQuiz(Game currentGame, Jury jury, StreamMethods streamMethods, SharedItems shared) {
		this.currentGame=currentGame;
		this.jury=jury;
		this.streamMethods=streamMethods;
		this.shared=shared;
	}
	
	@Override
	public void run() {
		ScreenMethods screen = new ScreenMethods();
		gameGUI = new GameJuryGUI(currentGame, shared);
		gameGUI.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		gameGUI.setSize(screen.getFullScreenX(), screen.getFullScreenY());
		gameGUI.setLocation(0,0);
		gameGUI.setUndecorated(true);
		gameGUI.setVisible(true);

		
		while(!currentGame.isEnded()){
			
			try {
				//Stap 5.1
				streamMethods.openObjectInputStream();
				currentGame = (Game) streamMethods.getObjectInput().readObject();
				gameGUI.setUpdatedGame(currentGame);
				
				System.out.println( " " + jury.getName() +  " has received a game with updated answerList");		
			}
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
			//Stap 5.2
			while( gameGUI.getInitialGame() == null ) {
				
				try {
					Thread.sleep(1000);
				} 
				catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				if ( gameGUI.getInitialGame() != null) {
					try {
						Thread.sleep(1000);
						//5.2
						streamMethods.openObjectOutputStream();
						streamMethods.getObjectOutput().writeObject(gameGUI.getInitialGame());
						//Info
						System.out.println( " JURY has sent a game with updated playerList");
					} 
					catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//System.err.println(updatedGame);
					catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}		
			gameGUI.setInitialGame(null);
		} 
	}

}
